/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import PropTypes from "prop-types";
import KbModal from "@/components/KbModal";
import { connect } from "dva";
import { isEmptyObject } from "@/utils/isSomeType";
import { cloneDeep } from "lodash";
import EditableTable from "./editTable";
import pageConfig from "./config";

@connect(({ loading, setter }) => ({
  setter,
}))
export default class Modal extends Component {
  constructor(props) {
    super(props);
    const { sourceType } = props;
    this.pageConfig = pageConfig(sourceType);
    this.state = {
      dataList: [],
      dataSource: [], // 编辑后表格所有的数据
      loading: false,
    };
    this.onOk = this.onOk.bind(this);
  }

  onOk = () => {
    const { dataList, dataSource } = this.state;
    const { hideModal, dispatch, user_id, page, cleanSelectRows } = this.props;
    const newAllTableData = cloneDeep(dataSource);

    if (dataList.length > 0) {
      this.setState({ loading: true });

      // 二次处理单号源编辑表格传过来的数据，主要处理未被编辑的数据
      newAllTableData.map((item, index) => {
        if (isEmptyObject(item.source)) {
          delete newAllTableData[index];
        }
        if (item.id < 0 || item.hasSelected) {
          // 当id小于0说明是新增，hasSelected判断单号源是否被修改
          delete item.id;
        }
        if (item.quantity == undefined) {
          // 当没有quantity说明是原有的数据
          item.quantity = 0; // 防止引用问题，设置为0是为了防止其他修改其他单号数量
          item.is_infinite = item.waybill_quantity < 0 ? "1" : "0"; // 0：有限，1：无限
        }

        if (item.is_infinite == 1) {
          // 无限单号
          item.quantity = -1;
        }
        if (item.price == null) {
          item.price = 0.0;
        }
        item.brand = item.brand_type || item.brand_type || item.brand;
        item.auth_id = item.source.auth_id;
        item.source_type = item.source.source_type;

        delete item.selectData;
        delete item.brand_name;
        delete item.brand_type;
        delete item.waybill_quantity;
        delete item.hasSelected;
        delete item.status_value;
        delete item.quantityForShow;

        return item;
      });

      const rules = newAllTableData.filter(val => val).map(item => JSON.stringify(item));
      // 当没有设置下拉单号源时，不请求数据
      if (rules.length == 0) {
        this.setState({ loading: false });
        hideModal();
        return;
      }
      const {
        actionTypes: { editOrderSource },
      } = this.pageConfig;
      dispatch({
        type: editOrderSource,
        payload: {
          rules,
          user_id,
        },
      })
        .then(res => {
          this.setState({
            loading: false,
            dataList: [],
            dataSource: [],
          });
          cleanSelectRows();
          // 刷新业务员列表
          const { actionTypes } = this.pageConfig;
          dispatch({
            type: actionTypes.getSetterList,
            payload: {
              page,
              site_id: "all",
              keyword: "",
            },
          });
        })
        .catch(err => {
          this.setState({
            loading: false,
            dataList: [],
            dataSource: [],
          });
        });
    }
    hideModal();
  };

  onCancel = () => {
    const { hideModal } = this.props;
    this.setState({
      dataList: [],
      dataSource: [],
    });
    hideModal();
  };

  add = () => {
    const { changeActiveKey, hideModal } = this.props;
    changeActiveKey("sources", "add"); // 当没有单号源时，跳转到单号源添加页面
    hideModal();
  };

  /**
   * 传递给单号源设置表格，来接收表格已编辑的数据，并将数据存在state中
   * @param {array} dataSource 编辑后的所有表格数据
   * @param {array} list 当前被编辑的数据
   */
  dataSourceChange = (dataSource, list) => {
    const { dataList } = this.state;
    const newDataList = cloneDeep(dataList);
    let rowList = {};
    const newDataSource = cloneDeep(dataSource);
    // 当单号源切换时，重置数据（单号价格，可用状态，单号数量）
    if (list.hasSelected) {
      rowList = {
        ...cloneDeep(list),
        price: 0.0,
        is_infinite: "1", // 默认无限
        quantity: "-1", // 默认无限
        waybill_quantity: -1,
        status: "1",
        hasSelected: true,
        quantityForShow: -1,
      };
      for (let i = 0; i < newDataSource.length; i++) {
        if (rowList.id == newDataSource[i].id) {
          newDataSource.splice(i, 1, rowList);
        }
      }
    } else {
      rowList = {
        ...cloneDeep(list),
      };
    }

    if (rowList) {
      for (let i = 0; i < newDataList.length; i++) {
        if (rowList.id === newDataList[i].id) {
          newDataList.splice(i, 1);
        }
      }
      newDataList.push(rowList);
      this.setState({
        dataList: newDataList,
      });
    }
    this.setState({
      dataSource: newDataSource,
    });
  };

  render() {
    const {
      visible,
      hideModal,
      okText,
      title,
      hasOrderSource,
      setter,
      tableData,
      dispatch,
      ...restProps
    } = this.props;
    const { dataSource, loading } = this.state;

    let editTableData;
    if (dataSource.length > 0) {
      editTableData = dataSource;
    } else {
      editTableData = tableData;
    }
    return (
      <KbModal
        destroyOnClose
        loading={loading}
        visible={visible}
        onCancel={this.onCancel}
        onOk={this.onOk}
        okText={hasOrderSource == "0" || hasOrderSource == undefined ? null : okText}
        title={title}
        width={1080}
        {...restProps}
        bodyStyle={{ textAlign: "center" }}
      >
        {hasOrderSource == "0" || hasOrderSource == undefined ? (
          <h2>
            暂无单号源
            <a style={{ marginLeft: 10 }} onClick={this.add}>
              去添加
            </a>
          </h2>
        ) : (
          <EditableTable tableData={editTableData} dataSourceChange={this.dataSourceChange} />
        )}
      </KbModal>
    );
  }
}
Modal.propTypes = {
  visible: PropTypes.bool.isRequired,
  wrappedComponentRef: PropTypes.func.isRequired,
  // onOk: PropTypes.func.isRequired,
  okText: PropTypes.string.isRequired,
  title: PropTypes.string.isRequired,
  // onCancel: PropTypes.func.isRequired,
  // status: PropTypes.any.isRequired,
  tableData: PropTypes.array.isRequired,
  changeActiveKey: PropTypes.func.isRequired,
};
